package com.thenmorethings.action;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.thenmorethings.entity.Essay;
import com.thenmorethings.entity.PageBean;
import com.thenmorethings.service.EssayService;

public class JsonAction extends ActionSupport{

	@Resource
	private EssayService essayService;
	
	
	public String EssayListJson()
	{
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			HttpServletRequest request = ServletActionContext.getRequest();
			response.setCharacterEncoding("UTF-8");
			request.setCharacterEncoding("UTF-8");
			String strPage = request.getParameter("page");
			if(strPage == null || strPage.trim().length() == 0)
			{
				strPage = "1";
			}
			Integer currPage = Integer.parseInt(strPage);
			
			/*
			 * 展现当前页
			 */
			PageBean pageBean = new PageBean();
			//封装当前页
			pageBean.setCurrPage(currPage);
			
			//封装总记录数
			Integer allRecord = essayService.findAll().size();
			pageBean.setAllPage(allRecord);
			
			//封装总页数
			Integer allPage = null;
			pageBean.setPageSize(4);
			if(pageBean.getAllPage() % pageBean.getPageSize() == 0)
			{
				allPage = pageBean.getAllPage() / pageBean.getPageSize();
			}
			else
			{
				allPage = pageBean.getAllPage() / pageBean.getPageSize() + 1;
			}
			
			//封装页面总页数
			pageBean.setAllPageSize(allPage);
			
			Integer start = (pageBean.getCurrPage()-1) * pageBean.getPageSize();
			Integer end = pageBean.getCurrPage() * pageBean.getPageSize();
			
			List<Essay> essayList = essayService.EssayPagination(start, pageBean.getPageSize());
			
			pageBean.setEssayList(essayList);
			
			Map<String,Object> map = new LinkedHashMap<String,Object>();
			map.put("total", pageBean.getAllPage());
			map.put("rows", pageBean.getEssayList());
			JSONArray json = JSONArray.fromObject(map);
			String jsonJAVA = json.toString();
			jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1);
			PrintWriter pw = response.getWriter();
			pw.write(jsonJAVA);
			pw.flush();
			pw.close();
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
